# -*- coding: utf-8 -*-
# $Id: mainwindow.py 27 2009-02-15 19:46:27Z gkuznets $
#
# Copyright 2008, 2009 Grigoriy Kuznetsov (gkuznets@yandex.ru)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QAction, QMainWindow, QIcon, QSplitter, QToolButton, QWidget,  QDockWidget, QListWidget, QLabel, QListView
from PyQt4.QtCore import QObject, QString, Qt, QTime, QTimer, SIGNAL

from aboutdialog import *
from core.batch import *
from batchproperties import *
from batchesmodel import BatchesModel
from commandline import CommandLine
from problemwidget import *
from hints import *
from markedmodel import MarkedModel

import checkup_rc
# Цвет иконок 00b200ff

class MainWindow(QMainWindow):
    """Главоне окно программы"""
  
    start_time = QTime.currentTime()
  
    def __init__(self, checkup):
        """Конструктор"""
        QMainWindow.__init__(self)
        self.checkup = checkup
        
        self.setWindowTitle(u"Проверка математического праздника")
        self.createActions()
        self.createLayout()
        self.fullscreen = False
        self.stat_window = None
        # Создаем посекундный таймер
        self.sec_timer = QTimer(self)
        # unflash-таймер
        self.unflash_timer = QTimer(self)
        self.unflash_timer.setSingleShot(True)
        self.unflash_timer.setInterval(100)
        self.createConnections()
        self.resize(1000, 700)
  
    def createActions(self):
        self.about_action = QAction(QIcon(), QString(u"О программе"), self)
        self.add_batch_action = QAction(QIcon(":/img/add_batch.png"), QString(u"Добавиь новую пачку работ"), self)
        self.run_action = QAction(QIcon(":/img/run.png"), QString(u"Начать проверку"), self)
        self.exit_action = QAction(QIcon(":/img/exit.png"), QString(u"Выход из программы"), self)
        self.show_statwindow_action = QAction(QIcon(":/img/exit.png"), QString(u"Окно статистики"), self)
    
    def createLayout(self):
        """Функция, конструирующая содержимое главного окна программы"""
        # Создаем панели инструментов
        tool_bar = self.addToolBar(u"Действия")
        tool_bar.addAction(self.add_batch_action)
        tool_bar.addSeparator()
        tool_bar.addAction(self.run_action)
        tool_bar.addSeparator()
        tool_bar.addAction(self.about_action)
        tool_bar.addAction(self.exit_action)
        tool_bar.addAction(self.show_statwindow_action)
        
        time_bar = self.addToolBar(u"Время")
        self.current_time_label = QLabel()
        self.elapsed_time_label = QLabel()
        time_bar.addWidget(self.current_time_label)
        time_bar.addWidget(self.elapsed_time_label)
        
        # Создаем серединку
        self.__central_list_view = QListView()
        self.__central_list_view.setViewMode(QListView.IconMode)
        self.__central_batches_model = BatchesModel(self)
        self.__central_list_view.setModel(self.__central_batches_model)
        self.setCentralWidget(self.__central_list_view)
        
        # Создаем плавающие окна
        # Группы
        self.groups = GroupsArea(self.checkup.problems_count)
        groups_dock_widget = QDockWidget(u"Группы проверки")
        groups_dock_widget.setWidget(self.groups)
        self.addDockWidget(Qt.TopDockWidgetArea, groups_dock_widget)
        # Свойства выделенной пачки
        self.batch_properties = BatchProperties()
        batch_properties_dock_widget = QDockWidget(u"Свойства пачки")
        batch_properties_dock_widget.setWidget(self.batch_properties)
        self.addDockWidget(Qt.BottomDockWidgetArea, batch_properties_dock_widget)
        # Подсказки
        self.hints = Hints()
        hints_dock_widget = QDockWidget(u"Подсказки")
        hints_dock_widget.setWidget(self.hints)
        self.addDockWidget(Qt.BottomDockWidgetArea, hints_dock_widget)
        # Пачки с ошибками (marked)
        self.__marked_view = QListView(self)
        self.__marked_model = MarkedModel(self)
        self.__marked_view.setModel(self.__marked_model)
        marked_dock_widget = QDockWidget(u"Помеченные")
        marked_dock_widget.setWidget(self.__marked_view)
        self.addDockWidget(Qt.RightDockWidgetArea, marked_dock_widget)
        
        # Создаем строку статуса
        status_bar = self.statusBar()
        self.command_line = CommandLine()
        status_bar.addWidget(self.command_line)
    
    def createConnections(self):
        # Действия
        self.connect(self.about_action, SIGNAL("triggered()"), self.show_about)
        self.connect(self.add_batch_action, SIGNAL("triggered()"), self.command_line.add)
        self.connect(self.run_action, SIGNAL("triggered()"), self.run)
        self.connect(self.exit_action, SIGNAL("triggered()"), self.close)
        self.connect(self.show_statwindow_action, SIGNAL("triggered()"), self.show_statwindow)
        # Виджеты
        self.connect(self.command_line, SIGNAL("toggle_fullscreen"), self.toggle_fullscreen)
        self.connect(self.command_line, SIGNAL("update"), self.updateAll)
        self.connect(self.command_line, SIGNAL("update_properties"), self.batch_properties.update)
        self.connect(self.command_line, SIGNAL("ChangesEvent"), self.__central_batches_model.onChanges)
        for w in self.groups.problemWidgets():
            self.connect(self.command_line, SIGNAL("groupChanged"), w.model().onGroupChanged)
            self.connect(self.hints, SIGNAL("groupChanged"), w.model().onGroupChanged)
        self.connect(self.command_line, SIGNAL("markedChanged"), self.__marked_model.onMarkedChanged)
        # Таймеры
        self.connect(self.sec_timer, SIGNAL("timeout()"), self.on_sec_timer)
        self.connect(self.unflash_timer, SIGNAL("timeout()"), self.unflash)
    
    def show_about(self):
        AboutDialog().exec_()
  
    def run(self):
        # Запустить провеку можно толко один раз, поэтому деактивируем run_action
        self.run_action.setEnabled(False)
        MainWindow.start_time = QTime.currentTime()
        self.sec_timer.start(1000)
        self.checkup.nextCheckup() # Начинаем первую проверку
        self.command_line.start()
        self.updateAll()
    
    def keyPressEvent(self, key_event):
        self.command_line.keyPressEvent(key_event)
    
    def updateAll(self):
        self.update()
        self.groups.update()
        #self.batches_list_widget.update()
        self.__central_list_view.update()
    
    def on_sec_timer(self):
        # Перерисовывем счетчики времен
        self.current_time_label.setText(QTime.currentTime().toString())
        # Генериуем подсказки
        self.hints.generate()
    
    def show_statwindow(self):
        from statwindow import StatWindow
        if self.stat_window == None:
            self.stat_window = StatWindow()
        self.stat_window.show()
    
    def flash(self, color):
        pass
    
    def unflash(self):
        pass
  
    def toggle_fullscreen(self):
        if self.fullscreen:
            self.showNormal()
        else:
            self.showFullScreen()
        self.fullscreen = not self.fullscreen
    
    def closeEvent(self, event):
        if self.stat_window is not None:
            self.stat_window.close()
        QMainWindow.closeEvent(self, event)